/** Class Name: iFulfillHandler
* Author: Accenture
* Date: 21-Jul-2011 
* Requirement/Project Name: iFulfill 
* Requirement Description: General. Methods invoked from Fulfillment Item trigger 
*  13/09/2011 Bhumika Udani    Added previous fields for req 710
*  22/09/2011 Bhumika Udani    Included the workflow status update line as defect fix # 241
*  10/11/2011 Bhumika Udani    Removed 'In progress' string value and replaced it with string constant
**/

public with sharing class iFulfillHandler{
//static var to prevent recursive trigger updates   
 private static boolean IsRecursive = true;
 public static boolean IsRecursive() {     
       return isRecursive;
 }        
 public static void setRecursive(boolean value) {     
       isRecursive=value;
 }


//copies the std owner into owner reporting field (for list views). also changes status based on whether the FI is moving into or out of the queue
public static void copyOwner(list<Fullfilment_Item__c> FI){
      List<id> itemOwnerIds = new List<id>();
      List<id> itemQueueIds = new List<id>();
      List<User> itemOwners = new list<User>();     
      List<QueueSobject> itemQueue = new list<QueueSobject>() ;      
      List<Fullfilment_Item__c> newItems = new List<Fullfilment_Item__c>();
      Map<id,String> OwnerMap = new Map<id,String>();
      QueueSobject queueData =[ Select q.QueueId from QueueSobject q where q.Queue.Name = :IfullfillTextConstant.WORKFLOWEXCEPTIONQUEUE Limit 1];           

      for(Fullfilment_Item__c Item :FI){
           if(((String)Item.ownerid).substring(0,3) == '005'){
               itemOwnerIds.add(Item.ownerid);
               Item.Status__c = IfullfillTextConstant.FI_WORKFLOW_PROGRESS_STATUS; // change status to In progress when owner is changed to 'USER'
           }
           else{           
             if(Item.ownerid == queueData.QueueId){
                Item.Status__c = IfullfillTextConstant.FI_WORKFLOW_UNASSIGNED_STATUS; //in case FI is moving exception Queue, change it to unassigned
             }else{
                 Item.Status__c = IfullfillTextConstant.FI_WORKFLOW_OPEN_STATUS; //change status to Open when owner is changed to 'Queue'
             }                   
             itemQueueIds.add(Item.ownerid);                                
           } 
         newItems.add(item);
       }
                
      if(itemOwnerIds.size()>0)  itemOwners = [select id, name from user where id in :itemOwnerIds];
      if(itemQueueIds.size()>0 ) itemQueue =[ Select q.QueueId, q.Queue.Name from QueueSobject q where q.queueid =: itemQueueIds];
      
      for(User U : itemOwners){
             OwnerMap.put(U.Id, U.Name);
         }
      
      for(QueueSobject Q : itemQueue ){
             OwnerMap.put(Q.QueueId, Q.Queue.Name);
         }
   
      
      for(Fullfilment_Item__c fItem : newItems){
            fItem.Owner_Reporting__c  = OwnerMap.get(fItem.ownerid);            
        }
}



    //Mark the last function/task for a workflow. Called from WorkflowController , edit and clone
    public static void updateLastTaskAndFunction(Id WFCode){
        String  funcName = null;
        String taskname = null;
        //select the last function of workflow
        List <Workflow_Stage__c> wfList = [Select w.Name, w.Is_last_Function__c  from Workflow_Stage__c w 
                                            where w.Workflow_Code__c  = :WFCode  order by sequence__c desc limit 1];                     
         if(wfList.size()>0)
         {
             funcName = wfList.get(0).name;
             wfList[0].Is_last_Function__c = true;
             System.debug(wfList.get(0).name );
             try{
                 update wfList;
              }catch(dmlException e){
                 GeneralCOnstants.mailAnyExceptionToMe('iFulfillHandler', 'updateLastTaskAndFunction', e );
             } 
         }  
         
         //select last task of workflow       
        List <Wokflow_Steps__c> taskList = [Select w.Name,id,w.Is_Last_Task__c  from Wokflow_Steps__c w  
                                                   where Wokflow_Stage_Name__r.name = :funcName  
                                                       and Wokflow_Stage_Name__r.Workflow_Code__c = :WFCode 
                                                           order by sequence__c desc limit 1];        
        if(taskList.size() > 0)
        {
             taskname = taskList.get(0).name;
             taskList[0].Is_Last_Task__c =true;
             try{
                 update taskList ;
              }catch(dmlException e){
                 GeneralCOnstants.mailAnyExceptionToMe('iFulfillHandler', 'updateLastTaskAndFunction', e );
             }             
        }       
    } 
    /*
     * Whenever user change the FI workflow status to outed the query request and quries must be closed.            
     *
     **/ 
    public static void closeQueryRequestAndQueries(Set<id> fids)
    {
         List <Queries__c>  queryList = new List <Queries__c>() ;
         List <Query_Request__c> queryRequestList = new List <Query_Request__c>();
 
         if(fids.size() > 0 )
         {
             queryRequestList = [select Request_Status__c  from Query_Request__c where  Fulfillment_Item__c in :fids];
             queryList = [select    Query_Status__c  from Queries__c where Query_Request_ID__c in :queryRequestList ];
             for(Query_Request__c qryReqObj : queryRequestList)
             {
                 qryReqObj.Request_Status__c = IfullfillTextConstant.QUERY_REQUEST_CLOSED_STATUS;
             }
             for ( Queries__c  qryObj : queryList )
             {
                 qryObj.Query_Status__c =  IfullfillTextConstant.QUERY_UNRESOLVED_STATUS;
             }
             
             try
             {
                              
                 update queryRequestList; 
                 update queryList;
             }
             catch(dmlException e)
             {
                 GeneralCOnstants.mailAnyExceptionToMe('iFulfillHandler', 'updateQueryRequest', e );
             }  
         }
    } 
   
      
}